package mrusanov.tournament

import mrusanov.team.{Team, Club}
import java.util.Date

class Tournament(val name:String, val rounds:Vector[TournamentRound]) {
  require(rounds.size > 0, "Rounds cann't be empty list!")

  var winner:Option[Team] = None
  var runnerUp:Option[Team] = None

  private var completed = false

  def round: Int = {
    rounds.zipWithIndex.view foreach {
      p => if (!p._1.isOver) {
        return p._2
      }
    }

    rounds.size
  }

  def initTournament(allClubs:List[Team]) {
    rounds(0).initTournamentRound(allClubs)
  }

  def updateTournament() {
    require(!completed, "Tournament already completed")

    if (isOver) {
      finishTournament()
      return
    }

    if (round == 0) {
      return
    }


    if (currentRound.initialized) {
      return
    }

    val prevRound = rounds(round - 1)

    assert(prevRound.isOver)
    assert(!currentRound.isOver)

    val passed = rounds(round - 1).passedRound
    prevRound.payReward()
    currentRound.initTournamentRound(passed)
  }

  def currentRound = rounds(round)

  private def finishTournament() {
    val lastRound = rounds(rounds.size - 1)
    val results = lastRound.resultsForReward

    winner = Some(results(0))
    runnerUp = Some(results(1))

    lastRound.payReward()

    completed = true
  }

  def isOver = round == rounds.size

  def matchesByDate(date:Date):List[MatchInfo] = {
    if (!isOver) {
      currentRound.allMatches.filter(_.time == date)
    } else {
      Nil
    }
  }

  def teamMatches(team:Team) = rounds.map(_.teamMatches(team)).flatten
}
